package com.example.loginpage

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import com.example.loginpage.CloudSQL.MySQLConnection
import com.example.loginpage.InputUtil.DataViewModel
import com.example.loginpage.databinding.FragmentUserBinding
import com.google.android.material.datepicker.MaterialDatePicker
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone

class UserFragment : Fragment() {
    private lateinit var binding: FragmentUserBinding
    private lateinit var mySQL: MySQLConnection
    private lateinit var dataViewModel: DataViewModel
    @SuppressLint("SetTextI18n")
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentUserBinding.inflate(layoutInflater,container, false)
        mySQL = ViewModelProvider(requireActivity())[MySQLConnection::class.java]
        dataViewModel = ViewModelProvider(requireActivity())[DataViewModel::class.java]

        mySQL.registerResponse.observe(requireActivity()){
            if (it != null){
                if (it.next()){
                    if (it.getString("username")!=null){
                        binding.UserNameText.text = it.getString("username")
                        dataViewModel.myUserName.postValue(it.getString("username"))
                    }
                    if (it.getString("sex")!=null){
                        dataViewModel.mySex.postValue(it.getString("sex"))
                        if(it.getString("sex") == "男"){
                            binding.GenderSpinner.setSelection(0)
                        } else{
                            binding.GenderSpinner.setSelection(1)
                        }
                    }
                    if(it.getString("birth")!=null){
                        binding.BirthText.text = it.getString("birth")
                        dataViewModel.myBirth.postValue(it.getString("birth"))
                    }
                }
            }
        }

        dataViewModel.myUserName.observe(requireActivity()){
            binding.UserNameText.text = it
        }
        dataViewModel.mySex.observe(requireActivity()){
            if(it == "男"){
                binding.GenderSpinner.setSelection(0)
            } else{
                binding.GenderSpinner.setSelection(1)
            }
        }
        dataViewModel.myBirth.observe(requireActivity()){
            binding.BirthText.text = it
        }
        binding.UserNameText.setOnClickListener {
            // 创建一个LayoutInflater来加载对话框的布局
            val layoutInflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            // Inflate the custom layout
            val view = layoutInflater.inflate(R.layout.custom_dialog, null)
            // Get the EditText from the custom layout
            val editText = view.findViewById<EditText>(R.id.editText)
            // 创建一个AlertDialog.Builder
            val builder = AlertDialog.Builder(requireContext())
            builder.setView(view)
            builder.setTitle("修改名称")
            builder.setPositiveButton("确定") { dialog, _ ->
                // 获取用户输入的文本并更新TextView
                if(editText.text.length > 10){
                    Toast.makeText(requireContext(), "用户名过长", Toast.LENGTH_SHORT).show()
                } else{
                    binding.UserNameText.text = editText.text
                    mySQL.updateSQL("UPDATE accounts SET username='${editText.text}' WHERE account='${binding.AccountNameText.text}';")
                }
                dialog.dismiss()
            }
            builder.setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }
            // 显示对话框
            builder.show()
        }

        binding.GenderSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                val selectedGender = parent.getItemAtPosition(position).toString()
                // 处理选中的性别
                mySQL.updateSQL("UPDATE accounts SET sex='${selectedGender}' WHERE account='${binding.AccountNameText.text}';")
            }
            override fun onNothingSelected(parent: AdapterView<*>) {
                // 用户没有选择任何选项时的处理
            }
        }

        binding.BirthText.setOnClickListener {
            // 创建 MaterialDatePicker 实例
            val datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择日期")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                .build()
            // 设置日期选择监听器
            datePicker.addOnPositiveButtonClickListener { selection ->
                // 将选择的日期转换为本地时间格式
                val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
                calendar.time = Date(selection)
                // 更新文本视图以显示选择的日期
                val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(calendar.time)
                binding.BirthText.text = formattedDate
                mySQL.updateSQL("UPDATE accounts SET birth='${formattedDate}' WHERE account='${binding.AccountNameText.text}';")
            }
            // 显示 MaterialDatePicker
            datePicker.show(childFragmentManager, "date_picker")
        }
        return binding.root
    }
    override fun onViewStateRestored(savedInstanceState: Bundle?) {
        super.onViewStateRestored(savedInstanceState)
        // 获取传递给MainActivity的Intent
        val activityIntent = requireActivity().intent
        // 从Intent中获取额外的数据
        binding.AccountNameText.text = activityIntent.getStringExtra(Activity_Account)
        mySQL.readSQL("Select username,sex,birth From accounts Where account='${binding.AccountNameText.text}'",2)
    }
}